package com.jiu345.users.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jiu345.users.mapper.UserMapper;
import com.jiu345.users.pojo.Member;
import com.jiu345.users.pojo.bo.AuthBo;
import com.jiu345.users.pojo.vo.AuthVo;
import com.jiu345.users.service.IAuthService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * package:IUserServiceImpl
 *
 * @author MrLei QQ:235921049
 * desc:用户信息
 * @Date 2024.07.05 15:17
 */
@RequiredArgsConstructor
@Service
public class IAuthServiceImpl implements IAuthService {
    private final UserMapper userMapper;
    /*用户注册*/
    @Override
    public R<Member> register(AuthBo bo) {
        //1验证验证码是否正确

        //验证输入的用户名对比数据库是否重复
        LambdaQueryWrapper<Member> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(Member::getUsername,bo.getUsername());
        List<Member> users = userMapper.selectList(userWrapper);
        if(users !=null && !users.isEmpty()){
//            throw new RuntimeException("手机号已占用！");
            return R.fail("手机号已占用！",null);
        }
        //
        Member member = new Member();
        //密码加密
        member.setPassword(BCrypt.hashpw(bo.getPassword()));
        member.setUsername(bo.getUsername());
        userMapper.insert(member);
        //保存用户信息
       return R.ok();
    }
    /*用户登录*/
    @Override
    public R<AuthVo> login(AuthBo bo) {
        LambdaQueryWrapper<Member> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(Member::getUsername, bo.getUsername());
        // 查询用户名
        Member member = userMapper.selectOne(userWrapper);
        if (member == null) {
//            throw new RuntimeException("用户名不存在");
            return R.fail("用户名不存在",null);
        }
        // 使用BCrypt来验证密码
        if (!BCrypt.checkpw(bo.getPassword(), member.getPassword())) {
//            throw new RuntimeException("密码错误");
            return R.fail("密码错误",null);
        }
        // 执行登录
        StpUtil.login(member.getId());

        // 封装返回信息
        AuthVo authVo = new AuthVo();
        authVo.setId(member.getId().toString());
        authVo.setUsername(member.getUsername());
        authVo.setToken(StpUtil.getTokenValue());
        return R.ok("登录成功",authVo);
    }
}
